package jh.com.jhappbf.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;

/**
 * @author Administrator
 */
public class ImageLoadHelper {
    private Context mAppContext;
    private ImageView mImageView;
    private ProgressBar mProgressBar;
    private String mId;
    private String mField;
    private WeakReference<Activity> mWeakReferenceActivity;

    public ImageLoadHelper(final Context mAppContext, ImageView imgView,
                           ProgressBar progressBar, WeakReference<Activity> activity) {
        super();
        this.mAppContext = mAppContext;
        this.mImageView = imgView;
        mProgressBar = progressBar;
        mWeakReferenceActivity = activity;

        mImageView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String value = String.valueOf(mImageView.getTag());
                if ("null".equals(value)) {
                    if (!TextUtils.isEmpty(mId) && !TextUtils.isEmpty(mField)) {
                        mProgressBar.setVisibility(View.VISIBLE);
                        loadImage(mField, mId);
                    }
                } else if (value.length() > 0) {
                    File file = new File(value);
                    if (file.exists()) {
                        Uri uri = Uri.fromFile(file);
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setDataAndType(uri, "image/*");
                        Activity activity = mWeakReferenceActivity.get();
                        if (activity != null) {
                            activity.startActivity(intent);
                        }
                    }
                }
            }
        });
    }

    /**
     * 判断文件是否已经存在
     *
     * @param path
     * @return
     */
    private Boolean imageExist(String path) {
        File f = new File(path);
        return f.exists();
    }

    /**
     * 获取图片的目录
     *
     * @return 图片目录
     */
    private String getImageDir() {
        boolean b = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        String directoryPath;
        if (b) {
            directoryPath = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/jinHeng";
        } else {
            directoryPath = mAppContext.getFilesDir().getAbsolutePath();
        }

        directoryPath += "/img";
        File f = new File(directoryPath);
        if (!f.exists()) {
            f.mkdir();
        }
        return directoryPath;
    }

    /**
     * 下载图片
     */
    public void loadImage(final String field, final String id) {

        mId = id;
        mField = field;
        String filePath = getImageDir() + "/" + id + field + "/.jpg";
        if (imageExist(filePath)) {
            return;
        }
        String methodName = "getImg";
        ArrayList<String> param = new ArrayList<>();
        param.add("field");
        param.add("id");
        ArrayList<String> value = new ArrayList<>();
        value.add(field);
        value.add(id);
        Listener<String> listener = response -> {
            mProgressBar.setVisibility(View.GONE);
            JSONObject obj = JsonHelper.getJsonObject(response);
            if (obj != null) {
                String result = obj.optString("result");

                // 保存文件
//                    BASE64Decoder decoder = new BASE64Decoder();
                try {
                    byte[] data = Base64.decode(result, Base64.DEFAULT);
//                        byte[] data = decoder.decodeBuffer(result);
                    saveImage(field, id, data);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        };

        ErrorListener errorListener = error -> {
            mProgressBar.setVisibility(View.GONE);
            mImageView.setImageResource(R.mipmap.load_error);
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }

    /**
     * 保存图片
     */
    private void saveImage(String field, String id, byte[] data) {
        if (data.length == 0) {
            Bitmap map = BitmapFactory.decodeResource(mAppContext.getResources(), R.mipmap.load_no_img);
            mImageView.setImageBitmap(map);
            return;
        }
//        Boolean b = Environment.getExternalStorageState().equals(
//                Environment.MEDIA_MOUNTED);

        String directoryPath = getImageDir();
        String path = directoryPath + "/" + id + field + ".jpg";
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(path);
            fout.write(data, 0, data.length);
            fout.close();
            setImage(path);
        } catch (Exception e) {
            mImageView.setImageResource(R.mipmap.load_error);
        } finally {
            if (fout != null) {
                try {
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    /**
     * 设置图片
     */
    private void setImage(String path) {
        DisplayMetrics metrics = mAppContext.getResources().getDisplayMetrics();
        int widthDst = metrics.widthPixels;
        int heightDst = metrics.heightPixels;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        int widthSrc = options.outWidth;
        int heightSrc = options.outHeight;

        int sampleSize = 1;
        if (widthSrc > widthDst || heightSrc > heightDst) {
            if (widthSrc > heightSrc) {
                sampleSize = Math.round(heightSrc / heightDst);

            } else {
                sampleSize = Math.round(widthSrc / widthDst);
            }
        }

        options.inSampleSize = sampleSize;
        options.inJustDecodeBounds = false;
        Bitmap img = BitmapFactory.decodeFile(path, options);
        mImageView.setImageBitmap(img);
        mImageView.setTag(path);
    }

    /**
     * 释放图片资源
     */
    public static void bitmapClear(ImageView image) {
        if (!(image.getDrawable() instanceof BitmapDrawable)) {
            return;
        }
//        BitmapDrawable bitmap = (BitmapDrawable) image.getDrawable();
//        Bitmap img = bitmap.getBitmap();
//        if (img != null&&!img.isRecycled()) {
//            img.recycle();
//            img=null;
//        }
        image.setImageDrawable(null);
    }
}
